<script setup>
// #ifdef H5 || APP-PLUS
import JSEncrypt from 'jsencrypt-plus';
// #endif
import System from '@/utils/system';
import { appStore } from '@/sotre/modules/app';

const { userInfo } = toRefs(appStore());

const $post = inject('$post');
const $get = inject('$get');

const { uniPlatform } = toRefs(System.info);
const title = ref('登录');
const loginForm = ref({
    account: '',
    password: '',
    remember: false,
    phone: '',
    code: '',
    agree: [true],
});
const loginRef = ref();
const showPassword = ref(false);

const codeTime = ref(0);
let codeTimer = null;

if (uniPlatform.value === 'mp-weixin') {
    title.value = '微信登录';
} else {
    title.value = '密码登录';
}

/**
 * 微信登录
 * @param e
 */
function getPhoneNumber(e) {
    if (e.detail.code) {
        uni.showLoading({
            title: '登录中...',
            mask: true,
        });
        $get(
            `/platform/wx/userInfoByPhone/${e.detail.code}?openid=${uni.getStorageSync('OPENID')}`
        ).then(res => {
            uni.hideLoading();
            if (res.code === 200 && res.data) {
                const user = res.data.userInfo.platformUsers;
                uni.setStorageSync('TEMP_TOKEN', res.data.access_token);
                userInfo.value = res.data.userInfo.platformUsers;
                if (user.state !== 0) {
                    uni.setStorageSync('TEMP_USER', user);
                    toRegister();
                } else {
                    uni.setStorageSync('TOKEN', res.data.access_token);
                    uni.setStorageSync('enterpriseId', user.lastEnterpriseId);
                    uni.switchTab({
                        url: '/pages/home/index',
                    });
                    return uni.showToast({
                        title: '登录成功',
                        icon: 'success',
                    });
                }
            } else {
                toRegister();
                uni.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000,
                });
            }
        });
    }
}

function getCode() {
    if (codeTime.value > 0) return;
    if (!loginForm.value.phone || loginForm.value.phone.length !== 11) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none',
        });
        return;
    }
    uni.showLoading({
        title: '获取中...',
        mask: true,
    });
    $post('/auth/platform/smsSend', {
        phone: loginForm.value.phone,
    }).then(res => {
        uni.hideLoading();
        if (res.code === 200) {
            uni.showToast({
                title: '验证码已发送',
                icon: 'success',
            });
            codeTime.value = 60;
            codeTimer = setInterval(() => {
                codeTime.value--;
                if (codeTime.value <= 0) {
                    clearInterval(codeTimer);
                    codeTimer = null;
                }
            }, 1000);
        }
    });
}

function changeTab(e) {
    title.value = e.name;
}

function toRegister() {
    if (userInfo.value.state === -2) {
        uni.navigateTo({
            url: '/pages/index/company?type=1',
        });
        return;
    }
    uni.navigateTo({
        url: '/pages/index/register',
    });
}

function toRecover() {
    uni.navigateTo({
        url: '/pages/index/recover',
    });
}

function loginFun() {
    loginRef.value.validate().then(({ valid }) => {
        if (valid) {
            uni.showLoading({
                title: '登录中...',
                mask: true,
            });
            if (loginForm.value.agree.length === 0) {
                uni.showToast({
                    title: '请先同意用户协议和隐私协议',
                    icon: 'none',
                });
                uni.hideLoading();
                return;
            }
            const data =
                title.value === '密码登录'
                    ? {
                          account: loginForm.value.account,
                          password: loginForm.value.password,
                      }
                    : {
                          phone: loginForm.value.phone,
                          code: loginForm.value.code,
                      };
            const str = JSON.stringify(data);
            const sign = encrypt(str);
            const url =
                title.value === '密码登录' ? '/auth/platform/login' : '/auth/platform/codeLogin';

            $post(url, { sign, sign }).then(res => {
                uni.hideLoading();
                if (res.code === 200) {
                    const user = res.data.userInfo.platformUsers;
                    userInfo.value = user;
                    if (user.state !== 0) {
                        uni.setStorageSync('TEMP_USER', user);
                        userInfo.value = user;
                        uni.setStorageSync('TEMP_TOKEN', res.data.access_token);
                        toRegister();
                    } else {
                        uni.setStorageSync('TOKEN', res.data.access_token);
                        uni.setStorageSync('enterpriseId', user.lastEnterpriseId);
                        uni.switchTab({
                            url: '/pages/home/index',
                        });
                    }
                }
            });
        }
    });
}

// #ifdef H5 || APP-PLUS
/**
 * 加密
 * @param str
 */
function encrypt(str) {
    const publicKey =
        'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCthNkZ2+IDVhfKbUO4cgeUOo1yIG1L4rCIcSYIAjaJGfihJdUzSmIIylc/2SKHuWQ2asgZNAZ/1Irw3/YUadTCD8ZqFfPiL3fbpS3DxIx97pz1vseWmT0zjq5Wps0butkxf6qH2dNV+8nwpIvdKZED+B6mEYjMx5qcPQq+T+4CSwIDAQAB';
    var encryptor = new JSEncrypt();
    encryptor.setPublicKey(publicKey);
    const result = encryptor.encryptLong(str);
    return result;
}
// #endif
</script>

<template>
    <div class="login">
        <u-navbar :title="title" left-icon="" placeholder></u-navbar>
        <div class="column" v-if="uniPlatform === 'mp-weixin'">
            <div class="logo">
                <wd-img src="/static/image/logo_person.png" width="150" mode="widthFix"></wd-img>
                <span>欢迎使用</span>
                <span style="font-size: 20px">硅基九尾狐AI应用商店</span>
            </div>
            <u-button type="warning" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
                手机号一键登录
            </u-button>
            <span>账号仅限特定人群或内部人员使用</span>
        </div>
        <div v-else class="web_login">
            <u-tabs
                :list="[{ name: '密码登录' }, { name: '手机号登录' }]"
                :activeStyle="{ color: '#f9702d' }"
                lineColor="#f9702d"
                lineWidth="50"
                @change="changeTab"
            ></u-tabs>
            <wd-form :model="loginForm" ref="loginRef">
                <template v-if="title === '密码登录'">
                    <wd-input
                        type="text"
                        v-model="loginForm.account"
                        placeholder="请输入手机号"
                        size="large"
                        prop="account"
                        :rules="[{ required: true, message: '请输入手机号' }]"
                        :maxlength="11"
                    />
                    <wd-input
                        :type="showPassword ? 'text' : 'password'"
                        v-model="loginForm.password"
                        placeholder="请输入密码"
                        prop="password"
                        size="large"
                        :rules="[{ required: true, message: '请输入密码' }]"
                        :maxlength="30"
                    >
                        <template #suffix>
                            <wd-icon
                                :name="showPassword ? 'view' : 'eye-close'"
                                size="22px"
                                @click="showPassword = !showPassword"
                            ></wd-icon>
                        </template>
                    </wd-input>
                </template>
                <template v-else>
                    <wd-input
                        type="text"
                        v-model="loginForm.phone"
                        placeholder="请输入手机号"
                        size="large"
                        prop="phone"
                        :rules="[{ required: true, message: '请输入手机号' }]"
                        :maxlength="11"
                    />
                    <wd-input
                        type="number"
                        v-model="loginForm.code"
                        placeholder="请输入验证码"
                        size="large"
                        prop="code"
                        :rules="[{ required: true, message: '请输入验证码' }]"
                        :maxlength="6"
                    >
                        <template #suffix>
                            <wd-button
                                type="text"
                                :disabled="codeTime > 0"
                                size="small"
                                @click="getCode"
                            >
                                {{ codeTime > 0 ? `${codeTime}s` : '获取验证码' }}
                            </wd-button>
                        </template>
                    </wd-input>
                </template>
                <div class="tools">
                    <wd-button type="text" @click="toRegister">注册</wd-button>
                    <wd-button type="text" v-if="title === '密码登录'" @click="toRecover">
                        忘记密码
                    </wd-button>
                </div>
                <u-button type="warning" size="large" @click="loginFun">立即登录</u-button>
            </wd-form>
        </div>
        <!-- <div class="tip">
            <u-checkbox-group v-model="loginForm.agree">
                <u-checkbox
                    shape="circle"
                    activeColor="#fb6f2e"
                    name="true"
                    label="登录代表同意"
                ></u-checkbox>
            </u-checkbox-group>
            <span style="color: #fb6f2e">《用户协议》</span>
            和
            <span style="color: #fb6f2e">《隐私协议》</span>
        </div> -->
    </div>
</template>

<style lang="scss" scoped>
.login {
    display: flex;
    flex-direction: column;
    height: 100vh;
    .web_login {
        padding: 30px 20px;
        :deep(.wd-form) {
            display: flex;
            flex-direction: column;
            padding: 50px 10px;
            .wd-input {
                background: transparent;
                .wd-icon {
                    background: transparent;
                    color: #fb6f2e;
                }
                button {
                    margin: 0;
                    font-weight: bold;
                    font-size: 14px;
                    color: #fb6f2e;
                }
            }
            .tools {
                display: flex;
                align-items: center;
                padding: 10px;
                gap: 20px;
                button {
                    margin: 0;
                    color: #fb6f2e;
                }
            }
            button {
                margin-top: 50px;
            }
        }
        :deep(.u-tabs__wrapper__nav__item__text) {
            font-size: 16px;
        }
    }
    .column {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding-top: 150px;
        gap: 30px;
        .logo {
            display: flex;
            align-items: center;
            flex-direction: column;
            font-size: 25px;
            gap: 15px;
        }
        :deep(.u-button) {
            width: 150px;
        }
    }
    .tip {
        font-size: 15px;
        color: #999;
        text-align: center;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: auto;
        margin-bottom: 20px;
        :deep(.u-checkbox) {
            margin: 0;
        }
    }
}
</style>
